

const baseUrl='https://tea.glike.top/marks/'; // 后端服务地址
const http_url='https://tea.glike.top/marks'; // 后端服务地址

const getSharePoint=(id,content)=>{
    let opts={
        url:'/qbgh/share',
        method: 'post'
    };
    let param={
       businessId:Number(id),
       shareContent:content?content:'分享',
    }
    httpTokenRequest(opts, param).then(res => {
    	console.log(res);
    }, error => {
    	console.log(error);
    })
}

//格式化链接地址
const prefix=(url)=>{
    if (url && url.startsWith('http')) {
      return url
    } else {
      url = `${http_url}${url}`
      return url
    }
}
//电话号码加密
const phoneStr=(phone)=>{
    if(phone!=''||phone!=undefined||phone!=null){
        var reg=/(\d{3})\d{4}(\d{4})/; //正则表达式
        phone= "" + phone;
        phone= phone.replace(reg, "$1****$2");
        return phone;
    }
}
const getToday=()=>{
	  const myDate = new Date()
	  const wk = myDate.getDay()
	  const yy = String(myDate.getFullYear())
	  const mm = (myDate.getMonth() + 1).toString().padStart(2, '0');
	  const dd = myDate.getDate().toString().padStart(2, '0');
	  const hou = String(
		myDate.getHours() < 10 ? '0' + myDate.getHours() : myDate.getHours()
	  )
	  const min = String(
		myDate.getMinutes() < 10
		  ? '0' + myDate.getMinutes()
		  : myDate.getMinutes()
	  )
	  const sec = String(
		myDate.getSeconds() < 10
		  ? '0' + myDate.getSeconds()
		  : myDate.getSeconds()
	  )
	  const weeks = [
		'星期日',
		'星期一',
		'星期二',
		'星期三',
		'星期四',
		'星期五',
		'星期六'
	  ]
	  const week = weeks[wk]
	  let nowDate = yy + '年' + mm + '月' + dd + '日'
	  let nowTime = hou + ':' + min + ':' + sec
	  let nowWeek = week
	  return nowDate;
	 }


//时间格式化
const parseTime=(time, pattern)=>{
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
	
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
//计算两个时间之间的时间差 多少天时分秒
const intervalTime=(new_date,old_date,format)=>{
    var subtime = (new_date - old_date) / 1000;    //计算时间差,并将毫秒转化为秒
    var days = parseInt(subtime / 86400);  //天  24*60*60*1000
    var hours = parseInt(subtime / 3600) - 24 * days;   //小时  60*60  总小时数-过去小时数=现在小时数
    var mins = parseInt(subtime % 3600 / 60);    //分钟 - (day*24)  以60秒为一整份  取余 剩下秒数 秒数/60就是分钟数
    var secs = parseInt(subtime % 60);   //以60秒为一整份  取余  剩下秒数
    let str='';
    if(days>0){
        str= days + "天 " + hours + "时" + mins + "分" + secs + "秒";
    }else{
        str= hours + "时" + mins + "分" + secs + "秒";
    }
    // console.log(str);
    if(format!=undefined){
        let arr=[];
        arr.push(secs);
        arr.push(mins);
        arr.push(hours);
        arr.push(days);
        // console.log(arr);
        str=JSON.stringify(arr);
    }
    return  str;
}


const loginout=()=>{
			let opts = {
				url:http_url+ '/logout',
				method: 'post'
			};
			let param = {};
			httpTokenRequest(opts, param).then(res => {
				console.log(res);
				uni.clearStorage();
				uni.switchTab({
				    url: '/pages/main/index'
				});
                
				
			}, error => {
				console.log(error);
			})
}

 const GetQueryString=(url,name)=>{
         var  reg =  new  RegExp( "(^|&)" + name + "=([^&]*)(&|$)" );
         var  r = url.match(reg);
         if (r!= null ) 
         return   unescape(r[2]);  
         return  null ;
   }
const httpTokenRequest = (opts, data, flag = 1) => {
	if (flag != 0) {
		// uni.showLoading({
		// 	title: '加载中...'
		// })
	}
	let token=uni.getStorageSync('token');
	let httpDefaultOpts = {
		url: http_url + opts.url,
		data: data,
		method: opts.method,
		header: {
			'Authorization':'Bearer '+token,
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json;charset=UTF-8",
		},
		dataType: 'json',
	}
	
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then((res) => {
				//接口报错
				if (res.statusCode != 200) {
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					})
					// return false;
				}
				
				//过期
				if (res.data.code == -1) {
					uni.showToast({
						title:'登录超时,请重新登录!',
						icon:'none',
					})
					uni.removeStorageSync('userinfo');
					uni.removeStorageSync('token');
					// return false;
				}
                if (res.data.code ==403) {
                	uni.showToast({
                		title:'没有权限,请联系管理员!',
                		icon:'none',
                	})
                	// return false;
                }
				//session不存在
				if (res.data.code == 401) {
                        uni.removeStorageSync('userinfo');
						uni.removeStorageSync('token');
						// uni.showToast({
						// 	title:'未登录,请先登录!',
						// 	icon:'none',
						// })
                        // 将跳转前的页面路径存储到本地存储中
                        // let prevPage=decodeURIComponent(getCurrentPages()[getCurrentPages().length - 1].$page.fullPath);
                        // uni.setStorageSync('prevPage',prevPage);
                        
                        // console.log('401-prevPage',prevPage);
                        // // console.log('401-prevPage-optipns',getCurrentPages()[getCurrentPages().length - 1].options);
                        // setTimeout(function(){
                        //    uni.switchTab({
                        //        url: '/pages/main/index',
                              
                        //    }); 
                        // },1000)
					// return false;
				}
				
				// if (res[1].data.code !=200) {
				// 	uni.showToast({
				// 		title: 'Error：' + res[1].data.msg,
				// 		icon: 'none'
				// 	})
				// 	return false;
					
				// }

				resolve(res.data)
			}
		).catch((response) => {
				uni.showToast({
					title: '系统报错,联系管理员',
					icon: 'none'
				})
				reject(response)
			}
		)
	})
	return promise
};
export default {
	baseUrl,
    http_url,
	httpTokenRequest,
    prefix,
    phoneStr,
    parseTime,
    intervalTime,
    getSharePoint,
    getToday
}


